import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import { Form, Row, Col, Icon, Modal, Input, message } from 'antd'
import ContentBox from 'components/contentBox'
import CustomTable from 'components/common/table'
import { PAGE_SIZE } from 'constants'
import { getPriceFilter } from 'utils/utils'
import PropTypes from 'prop-types'

import Style from './userDetails.css'

const payWay = {
  WECHART: '微信支付',
  ALIPAY: '支付宝'
}
const source = {
  'APP_ORDER': 'APP订单',
  'PC_CUSTOM_ORDER': 'PC定制订单'
}
const status = {
  0: '待支付',
  10: '待发货',
  20: '待收货',
  30: '已完成',
  40: '待退货',
  41: '退货中',
  42: '退货成功',
  50: '待退款',
  51: '退款中',
  52: '退款成功',
  98: '取消交易',
  99: '订单关闭'
}
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 }
}
class UserDetails extends Component {
  static propTypes = {
    match: PropTypes.any,
    getUserDetails: PropTypes.func,
    userDetail: PropTypes.any,
    router: PropTypes.any
  }
  constructor (props) {
    super(props)
    this.state = {
      pageSize: PAGE_SIZE,
      pageNo: 1,
      showAgreement: false,
      currentContent: ''
    }
    this.showSetting = this.showSetting.bind(this)
    this.hideSetting = this.hideSetting.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.auditSubmit = this.auditSubmit.bind(this)
  }

  getAddressCols () {
    return [
      {
        title: '姓名',
        dataIndex: 'consigneeName',
        key: 'consigneeName',
        width: 100
      },
      {
        title: '手机号码',
        dataIndex: 'consigneeMobile',
        key: 'consigneeMobile',
        width: 100
      },
      {
        title: '详细地址',
        dataIndex: 'goodsType',
        key: 'goodsType',
        width: 100,
        render: (text, record) => {
          return `${record.belongArea}${record.addressDetails}`
        }
      },
      {
        title: '邮政编码',
        dataIndex: 'status',
        key: 'status',
        width: 100
      }
      // {
      //   title: '默认地址',
      //   dataIndex: 'order',
      //   key: 'order',
      //   width: 100,
      //   render: () => {
      //     return <Switch />
      //   }
      // }
    ]
  }

  getUsersTableCols () {
    return [
      {
        title: '用户Id',
        dataIndex: 'goodsTitle',
        key: 'goodsTitle',
        width: 100
      },
      {
        title: '用户手机号',
        dataIndex: 'goodsPrice',
        key: 'goodsPrice',
        width: 100
      },
      {
        title: '用户名称',
        dataIndex: 'goodsType',
        key: 'goodsType',
        width: 100
      },
      {
        title: '用户类型',
        dataIndex: 'lll',
        key: 'lll',
        width: 100
      },
      {
        title: '收藏数量',
        dataIndex: 'order',
        key: 'order',
        width: 100
      }
    ]
  }

  getOrderCols () {
    return [
      {
        title: '订单编号',
        dataIndex: 'orderNo',
        key: 'orderNo',
        width: 100,
        sorter: (a, b) => a.orderNo - b.orderNo
      },
      {
        title: '提交时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 100,
        sorter: (a, b) => a.createTime - b.createTime
      },
      {
        title: '用户名称',
        dataIndex: 'consigneeName',
        key: 'consigneeName',
        width: 100
      },
      {
        title: '订单金额',
        dataIndex: 'orderAmount',
        key: 'orderAmount',
        width: 100,
        render: n => `¥${getPriceFilter(n)}`,
        sorter: (a, b) => a.orderAmount - b.orderAmount
      },
      {
        title: '支付方式',
        dataIndex: 'payChannel',
        key: 'payChannel',
        width: 100,
        render: text => payWay[text]
      },
      {
        title: '订单来源',
        dataIndex: 'orderResource',
        key: 'orderResource',
        width: 100,
        render: text => source[text]
      }, {
        title: '订单状态',
        dataIndex: 'orderStatus',
        key: 'orderStatus',
        width: 100,
        render: text => status[text]
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        width: 100,
        render: (text, record) => {
          return (<>
            <a className={Style['a-btn']} onClick={() => this.props.router.push(`/order/details/${record.orderId}`)}>查看详情</a>
            <a className={Style['a-btn']} onClick={() => this.handleShowAgreement(record)}>协议</a>
          </>)
        }
      }
    ]
  }

  componentDidMount () {
    const { id } = this.props.match.params
    this.id = id
    this.props.getUserDetails({
      userId: id
    })
    this.props.getAddressList({
      userId: id
    })
    this.getOrderList()
  }

  getOrderList () {
    const { pageSize, pageNo } = this.state
    this.props.getOrderList({
      userId: this.id,
      pageSize,
      pageNo
    })
  }

  onPageChange (pageNo, pageSize) {
    const params = {
      userId: this.id
    }
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getOrderList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const params = {
      userId: this.id
    }
    params.pageNo = current
    params.pageSize = pageSize
    this.props.getOrderList(params)
  }

  showSetting () {
    this.setState({
      showSetting: true
    })
  }

  hideSetting () {
    this.setState({
      showSetting: false
    })
  }

  auditSubmit () {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.userId = this.id
        this.props.saveLabel(values).then(() => {
          this.props.getUserDetails({
            userId: this.id
          })
        })
        this.setState({
          showSetting: false
        })
      }
    })
  }

  handleShowAgreement = record => {
    this.setState({
      currentContent: record.agreementContent,
      showAgreement: true
    })
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.saveLabelRequest && nextProps.saveLabelRequest) {
      message.success('保存成功')
    }
  }

  render () {
    const { userDetail, addressList, orderData } = this.props
    const { pageNo, showSetting, showAgreement, currentContent } = this.state
    const { getFieldDecorator } = this.props.form
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: orderData && orderData.total,
      onChange: this.onPageChange,
      pageSize: PAGE_SIZE,
      onShowSizeChange: this.onShowSizeChange
    }
    return (
      <>
        <ContentBox>
          <div className={Style['users-manage-user-details']}>
            <div className={Style['users-info-container']}>
              <Row gutter={24} style={{ height: '100%' }}>
                <Col span={8} style={{ height: '100%', padding: '0px' }}>
                  <div className={Style['user']}>
                    <div className={Style['setting']} onClick={this.showSetting}>
                      <Icon type='setting' />
                    </div>
                    <div className={Style['avatar']} style={{ backgroundImage: `url(${userDetail.avatar})` }} />
                    <div className={Style['name']}>{userDetail.name}</div>
                    <div className={Style['status']}>{userDetail.memberLevel}</div>
                    <div style={{ marginTop: '10px' }}>{userDetail.label}</div>
                  </div>
                </Col>
                <Col span={8} style={{ height: '100%', padding: '0px' }}>
                  <div className={Style['user']}>
                    <div className={Style['item-container']}>
                      <div className={Style['label']}>用户Id</div>
                      <div className={Style['value']}>{userDetail.userId}</div>
                    </div>
                    <div className={Style['item-container']}>
                      <div className={Style['label']}>用户名称</div>
                      <div className={Style['value']}>{userDetail.name}</div>
                    </div>
                    <div className={Style['item-container']}>
                      <div className={Style['label']}>性别</div>
                      <div className={Style['value']}>{userDetail.gender}</div>
                    </div>
                    <div className={Style['item-container']}>
                      <div className={Style['label']}>生日</div>
                      <div className={Style['value']}>{userDetail.birth}</div>
                    </div>
                    <div className={Style['item-container']}>
                      <div className={Style['label']} style={{ borderBottom: 'none' }}>城市</div>
                      <div className={Style['value']} style={{ borderBottom: 'none' }}>{userDetail.city}</div>
                    </div>
                  </div>
                </Col>
                <Col span={8} style={{ height: '100%', paddingLeft: '0px' }}>
                  <div className={Style['user']}>
                    {/* <div className={Style['item-container']}>
                      <div className={Style['label']}>用户手机号</div>
                      <div className={Style['value']}>{userDetail.userId}</div>
                    </div> */}
                    <div className={Style['item-container']}>
                      <div className={Style['label']}>手机号码</div>
                      <div className={Style['value']}>{userDetail.mobile}</div>
                    </div>
                    <div className={Style['item-container']}>
                      <div className={Style['label']}>注册时间</div>
                      <div className={Style['value']}>{userDetail.createTime}</div>
                    </div>
                    <div className={Style['item-container']}>
                      <div className={Style['label']}>付会员到期时间</div>
                      <div className={Style['value']}>{userDetail.memberEndTime}</div>
                    </div>
                    <div className={Style['item-container']}>
                      <div className={Style['label']} >用户来源</div>
                      <div className={Style['value']} >{userDetail.city}</div>
                    </div>
                    <div className={Style['item-container']} >
                      <div className={Style['label']} style={{ borderBottom: 'none' }}>标签</div>
                      <div className={Style['value']} style={{ borderBottom: 'none' }} >{userDetail.label}</div>
                    </div>
                  </div>
                </Col>
              </Row>
            </div>
            <div className={Style['title']}>统计信息</div>
            <div className={Style['table-container']}>
              <div className={Style['statistics-container']}>
                <div className={Style['statistics-block']}>
                  {/* <div className={Style['statistics-item']}>
                    <div className={Style['header-title']} style={{ color: 'red' }}>未读消息</div>
                    <div className={Style['statistics-value']}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.unReadMsg
                      }
                    </div>
                  </div> */}
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>消费金额</div>
                    <div className={Style['statistics-value']}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.consumptionAmount ? `¥${getPriceFilter(userDetail.statisticInfo.consumptionAmount)}` : null
                      }
                    </div>
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>订单数量</div>
                    <div className={Style['statistics-value']}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.orderCount
                      }
                    </div>
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>可用积分</div>
                    <div className={`${Style['statistics-value']} ${Style['active']}`} onClick={() => this.props.router.push(`/users/integral/detail/${userDetail.userId}`)}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.residueIntegration
                      }
                    </div>
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>购物车</div>
                    <div className={`${Style['statistics-value']} ${Style['active']}`} onClick={() => this.props.router.push(`/users/manage/shoppingcar-details/${userDetail.userId}`)}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.shopCartCount
                      }
                    </div>
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>退货记录</div>
                    <div className={Style['statistics-value']}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.salesReturnRecord
                      }
                    </div>
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>邀请好友</div>
                    <div className={`${Style['statistics-value']} ${Style['active']}`} onClick={() => this.props.router.push(`/users/invite/details/${userDetail.userId}`)}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.invitedCount
                      }
                    </div>
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>登陆次数</div>
                    <div className={`${Style['statistics-value']} ${Style['active']}`} style={{ borderBottom: 'none' }} onClick={() => this.props.router.push(`/users/manage/login-details/${userDetail.userId}`)}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.loginCount
                      }
                    </div>
                  </div>
                  {/* <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>未读动态</div>
                    <div className={Style['statistics-value']}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.unReadDynamic
                      }
                    </div>
                  </div> */}
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>收藏</div>
                    <div className={`${Style['statistics-value']} ${Style['active']}`} style={{ borderBottom: 'none' }} onClick={() => this.props.router.push(`/users/manage/collection-details/${userDetail.userId}`)}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.collectCount
                      }
                    </div>
                  </div>
                </div>
                <div className={Style['statistics-block']}>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>关注</div>
                    <div className={`${Style['statistics-value']} ${Style['active']}`} style={{ borderBottom: 'none' }} onClick={() => this.props.router.push(`/users/manage/follow-details/${userDetail.userId}`)}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.attentionCount
                      }
                    </div>
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']}>点赞</div>
                    <div className={`${Style['statistics-value']} ${Style['active']}`} style={{ borderBottom: 'none' }} onClick={() => this.props.router.push(`/users/manage/like-details/${userDetail.userId}`)}>
                      {
                        userDetail.statisticInfo && userDetail.statisticInfo.likeCount
                      }
                    </div>
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']} />
                    <div className={Style['statistics-value']} style={{ borderBottom: 'none' }} />
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']} />
                    <div className={Style['statistics-value']} style={{ borderBottom: 'none' }} />
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']} />
                    <div className={Style['statistics-value']} style={{ borderBottom: 'none' }} />
                  </div>
                  <div className={Style['statistics-item']}>
                    <div className={Style['header-title']} />
                    <div className={Style['statistics-value']} style={{ borderBottom: 'none' }} />
                  </div>
                </div>
              </div>
            </div>
            <div className={Style['title']}>收货地址</div>
            <div className={Style['table-container']}>
              <CustomTable bordered loading={false} columns={this.getAddressCols()} dataSource={addressList} pagination={false} />
            </div>
            <div className={Style['title']}>订单记录</div>
            <div className={Style['table-container']}>
              <CustomTable bordered loading={!orderData} columns={this.getOrderCols()} dataSource={(orderData && orderData.list) || []} pagination={pagination} />
            </div>
            <Modal
              title='编辑标签'
              destroyOnClose
              visible={showSetting}
              width={600}
              onOk={this.auditSubmit}
              onCancel={this.hideSetting}>
              <Form {...layout} >
                <Form.Item label='标签' help='多个标签请用","隔开'>
                  {
                    getFieldDecorator('label', {
                      rules: [{ required: true, message: '输入' }],
                      initialValue: userDetail.label
                    })(
                      <Input placeholder='请输入' />
                    )
                  }

                </Form.Item>
              </Form>
            </Modal>
            <Modal
              title='协议详情'
              visible={showAgreement}
              onCancel={() => this.setState({ showAgreement: false })}
              footer={false}
              bodyStyle={{ maxHeight: 520, overflow: 'auto' }}
            >
              <div dangerouslySetInnerHTML={{ __html: currentContent }} />
            </Modal>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  userDetail: state.users.userDetail || {},
  addressList: state.users.addressList || [],
  orderData: state.users.orderData,
  saveLabelRequest: state.users.saveLabelRequest
})
const mapDispatch = dispatch => ({
  getUserDetails: dispatch.users.getUserDetails,
  getAddressList: dispatch.users.getAddressList,
  getOrderList: dispatch.users.getOrderList,
  saveLabel: dispatch.users.saveLabel
})
const FormUserDetails = Form.create()(UserDetails)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(FormUserDetails)
)
